package com.qk.util;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.qk.util.property.AliyunOSSProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * STS临时令牌获取工具类
 */
@Component
@Slf4j
@SuppressWarnings("all")
public class STSUtils {

    @Autowired
    private AliyunOSSProperties aliyunOSSProperties;

    private static final String[] IPSERVICES = {
            "https://ipinfo.io/ip",
            "https://api.ipify.org",
            "https://checkip.amazonaws.com"
    };
    private static final int SUCCESS_CODE = 200;

    /**
     * 获取当前公网IP
     */
    public String getCurrentPublicIP() {
        for (String service : STSUtils.IPSERVICES) {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpGet request = new HttpGet(service);
                try (CloseableHttpResponse response = httpClient.execute(request)) {
                    if (response.getStatusLine().getStatusCode() == SUCCESS_CODE) {
                        HttpEntity entity = response.getEntity();
                        String ip = entity != null ? EntityUtils.toString(entity).trim() : null;
                        if (ip != null && !ip.isEmpty()) {
                            log.info("从 {} 获取到公网IP: {}", service, ip);
                            return ip;
                        }
                    }
                }
            } catch (IOException e) {
                log.warn("从 {} 获取公网IP失败: {}", service, e.getMessage());
            }
        }

        log.error("所有公网IP服务都不可用");
        return null;
    }

    /**
     * 生成动态策略文档
     */
    private String generatePolicyDocument(String currentIp, String bucketName) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            ObjectNode policyNode = mapper.createObjectNode();
            policyNode.put("Version", "1");

            ObjectNode statement = mapper.createObjectNode();
            statement.put("Effect", "Allow");

            // 允许的操作列表 - 根据您的需求调整
            statement.putArray("Action")
                    .add("oss:PutObject")
                    .add("oss:GetObject")
                    .add("oss:DeleteObject")
                    .add("oss:ListObjects")
                    .add("oss:AbortMultipartUpload")
                    .add("oss:ListParts");

            // 资源限制 - 替换为您的bucket名称
            statement.putArray("Resource")
                    .add("acs:oss:*:*:" + bucketName)
                    .add("acs:oss:*:*:" + bucketName + "/*");

            // IP条件限制 - 核心安全措施！
            /*if (currentIp != null && !currentIp.isEmpty()) {
                ObjectNode condition = mapper.createObjectNode();
                ObjectNode ipAddress = mapper.createObjectNode();
                ipAddress.putArray("acs:SourceIp").add(currentIp + "/32");
                condition.set("IpAddress", ipAddress);
                statement.set("Condition", condition);
            }*/

            policyNode.set("Statement", mapper.createArrayNode().add(statement));
            return mapper.writeValueAsString(policyNode);

        } catch (Exception e) {
            System.err.println("生成策略文档失败: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取STS临时令牌
     */
    public AssumeRoleResponse.Credentials getSTSToken(String bucketName) {
        try {
            // 配置客户端
            DefaultProfile profile = DefaultProfile.getProfile(
                    aliyunOSSProperties.getRegion(),
                    aliyunOSSProperties.getAccessKeyId(),
                    aliyunOSSProperties.getAccessKeySecret());
            IAcsClient client = new DefaultAcsClient(profile);

            // 构建请求
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.setRoleArn(aliyunOSSProperties.getRoleArn());
            request.setRoleSessionName("springboot-oss-" + System.currentTimeMillis());
            request.setDurationSeconds(aliyunOSSProperties.getDurationSeconds());

            // 获取当前IP并生成动态策略
            // String currentIp = getCurrentPublicIP();
            String policy = generatePolicyDocument(null, bucketName);
            /*if (policy != null) {
                request.setPolicy(policy);
            }*/
            request.setPolicy(policy);

            // 调用STS服务
            AssumeRoleResponse response = client.getAcsResponse(request);
            log.info("STS令牌获取成功，过期时间: " + response.getCredentials().getExpiration());

            return response.getCredentials();

        } catch (ClientException e) {
            log.error("获取STS令牌失败 - Error Code: {}, Message: {}",
                    e.getErrCode(), e.getErrMsg());
            return null;
        }
    }

    /**
     * 使用默认bucket获取STS令牌
     */
    public AssumeRoleResponse.Credentials getSTSToken() {
        return getSTSToken(aliyunOSSProperties.getBucketName());
    }
}